package com.dxb.hystrix.comsumer.controller;


import com.dxb.hystrix.comsumer.command.UserTimeoutCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author DLS
 */
@RestController
@RequestMapping("hello")
public class HelloController {

    @GetMapping("timeout")
    @HystrixCommand(fallbackMethod = "helloFallback",
            threadPoolProperties = {
                    @HystrixProperty(name = HystrixPropertiesManager.CORE_SIZE, value = "20"),
                    @HystrixProperty(name = HystrixPropertiesManager.MAXIMUM_SIZE, value = "20")
            },
            commandProperties = {
                    @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "1000")
            })
    public String hello() throws InterruptedException {
        System.out.println("hello timeout");
        Thread.sleep(3000);
        return "Welcome hello";
    }

    private String helloFallback() {
        System.out.println("hello fallback");
        return "hello fallback";
    }

    @GetMapping("semaphore")
    @HystrixCommand(fallbackMethod = "semaphoreFallback",
            commandProperties = {
                    @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_STRATEGY, value = "SEMAPHORE"),
                    @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, value = "3"),
                    @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "10000")
            })
    public String semaphore() throws InterruptedException {
        System.out.println("semaphore");
        Thread.sleep(3000);
        return "Welcome semaphore";
    }

    private String semaphoreFallback() {
        System.out.println("semaphore fallback");
        return "semaphore fallback";
    }

    @GetMapping("command")
    public String commandClass() {
        return new UserTimeoutCommand().execute();
    }
}
